package com.yzg.simple.netty.unpacking.unpacking_solve.server;

import com.yzg.simple.netty.unpacking.unpacking_solve.protocol.MessageProtocol;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.util.UUID;

/**
 * @author misterWei
 * @create 2019年12月26号:23点02分
 * @mailbox mynameisweiyan@gmail.com
 *
 * 对服务器Handler 进行处理做业务操作
 *
 * 基于解决Netty TCP 粘包拆包 示例代码
 */
public class ServerHandler extends SimpleChannelInboundHandler<MessageProtocol>{
    private int limit;





    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //异常处理一般都是关闭当前管道
        ctx.close();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol mes) throws Exception {
        System.out.println("服务读了 " + ++ this.limit + "次.");
        System.out.println("长度为"+ mes.getLen());
        System.out.println(new String(mes.getContent(), CharsetUtil.UTF_8));
       //回复客户端 相当于 客户端只要数据包过来一次,服务端这边就会回应一次;
        String mesInfo = UUID.randomUUID().toString().replace("-","~");
        byte[] mesInfoBytes = mesInfo.getBytes();
        ctx.writeAndFlush(new MessageProtocol(mesInfoBytes.length,mesInfoBytes));
    }
}
